package com.fdb.smcts.web.http;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.Cookie;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import com.fdb.smcts.core.vo.EngineHttpRequestVO;
import com.fdb.smcts.core.vo.EngineHttpResponseVO;

/**
 * restful api调用
 * @param <I>
 * 
 * @author Cytus_
 * @since 2018年5月11日 下午3:04:12
 * @version 1.0
 *
 */
public class EngineRestfulHttpClient implements EngineHttpClient {

	public EngineHttpResponseVO httpCall(String url, EngineHttpRequestVO reqVO, Class<EngineHttpResponseVO> clazz) throws Exception{

		RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory());
		
		List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
		Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
		while (iterator.hasNext()) {
			HttpMessageConverter<?> converter = iterator.next();
			if (converter instanceof StringHttpMessageConverter) {
				iterator.remove();
			}
		}
		messageConverters.add(new StringHttpMessageConverter(Charset.forName("utf-8")));
		
		HttpHeaders headers = new HttpHeaders();
		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		HttpEntity<EngineHttpRequestVO> entity = new HttpEntity<EngineHttpRequestVO>(reqVO, headers);
		
		ResponseEntity<EngineHttpResponseVO> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, EngineHttpResponseVO.class, new Object[]{});
		return responseEntity.getBody();
	}

	@Override
	public void setHeader(String key, String value) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setCookie(Collection<Cookie> cookies) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public EngineHttpResponseVO httpCall(String url, HttpMethod method, EngineHttpRequestVO inArgs, Class<EngineHttpResponseVO> clazz,
			Object... params) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	
	

}
